package com.baibei.ebec.home.newIndex;

import android.app.Dialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.AnimationDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baibei.ebec.home.R;
import com.baibei.ebec.home.R2;
import com.baibei.ebec.home.index.listener.OnSelectListener;
import com.baibei.ebec.sdk.TokenInfo;
import com.baibei.ebec.totrade.ToTradeFragment;
import com.baibei.model.Area;
import com.baibei.model.BalanceInfo;
import com.baibei.model.BannerInfo;
import com.baibei.model.CouponInfo;
import com.baibei.model.CouponResponseInfo;
import com.baibei.model.CustomerWxInfo;
import com.baibei.model.HomeIndexInfo;
import com.baibei.model.HomeIndexProductInfo;
import com.baibei.model.MsgStatusInfo;
import com.baibei.model.NewMarqueeInfo;
import com.baibei.model.OrderInfo;
import com.baibei.model.ProductInfo;
import com.baibei.model.QuotationProductInfo;
import com.baibei.model.RankingInfo;
import com.baibei.model.ShipmentInfo;
import com.baibei.model.TradeTimeInfo;
import com.baibei.model.TradeType;
import com.baibei.model.UserInfo;
import com.baibei.model.XinStatusInfo;
import com.baibei.model.event.LoginEvent;
import com.baibei.module.AppRouter;
import com.baibei.module.BasicFragment;
import com.baibei.module.OnItemSelectListener;
import com.baibei.module.ViewUtil;
import com.baibei.module.stock.simple.SimpleStockFragment;
import com.baibei.ui.AppUI;
import com.baibei.widget.CommonRefreshLayout;
import com.baibei.widget.JustifyTextView;
import com.baibei.widget.PriceTextView;
import com.blankj.utilcode.utils.ScreenUtils;
import com.blankj.utilcode.utils.ToastUtils;
import com.bumptech.glide.Glide;
import com.rae.swift.Rx;
import com.rae.swift.session.SessionManager;
import com.rae.widget.dialog.DialogBuilder;
import com.sunfusheng.marqueeview.MarqueeView;
import com.youth.banner.Banner;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;

import static android.content.ContentValues.TAG;

/**
 * Created by tang on 2018/6/27.
 */

public class NewHomeIndexFragment extends BasicFragment implements NewHomeIndexContract.View, OnSelectListener<ProductInfo>, OnItemSelectListener<ProductInfo> {
    @BindView(R2.id.marquee)
    MarqueeView marquee;
    @BindView(R2.id.banner)
    Banner banner;
    Unbinder unbinder;
    @BindView(R2.id.fl_chart)
    FrameLayout flChart;
    @BindView(R2.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R2.id.recyclerView2)
    RecyclerView recyclerView2;
    @BindView(R2.id.tv_balance)
    TextView tvBalance;
    @BindView(R2.id.lin_balance)
    LinearLayout linBalance;
    @BindView(R2.id.tv_order)
    PriceTextView tvOrder;
    @BindView(R2.id.lin_order)
    LinearLayout linOrder;
    @BindView(R2.id.tv_coupon)
    TextView tvCoupon;
    @BindView(R2.id.lin_coupon)
    LinearLayout linCoupon;
    @BindView(R2.id.refresh_layout)
    CommonRefreshLayout refreshLayout;
    @BindView(R2.id.iv_new)
    ImageView ivNew;
    @BindView(R2.id.iv_xiaoxi)
    ImageView ivXiaoxi;
    @BindView(R2.id.iv_help)
    ImageView ivHelp;
    private NewHomeIndexContract.Presenter mPresenter;
    private ArrayList<String> urls;
    private ArrayList<Fragment> mFragmentList;
    private HomeIndexInfo homeIndexInfo;
    private int productPosition; //商品下标
    private int stairPosition; //贵金属大类下标
    private List<QuotationProductInfo> quotationProductInfoList = new ArrayList<>();
    private QuotationProductInfo quotationProductInfo;
    private List<ProductInfo> productInfos;
    private CommodityAdapter mCommodityAdapter;
    private ProductAdapter mProductAdapter;
    private List<CouponInfo> couponInfos;
    private ToTradeFragment toTradeFragment;
    private List<RankingInfo> rankingInfoList;
    private List<NewMarqueeInfo> marqueeInfos;
    private boolean ifChartIsAdded;
    private String helpContent;
    private List<CouponInfo> productCoupons;
    private TradeType buyOrSell = TradeType.BUY;
    private SimpleStockFragment simpleStockFragment;
    private CustomerWxInfo customerWxInfo;

    @Override
    public int getLayoutId(Bundle bundle) {
        return R.layout.fragment_index_new;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPresenter = inject(NewHomeIndexContract.Presenter.class);

        mPresenter.start();
        mPresenter.getMarquee();
        mPresenter.getHelp();
        mPresenter.getIfShowXin();
        mPresenter.getCustomerWxCode();
        checkIfHasNewMsg();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
//        mPresenter.getMarquee();
        recyclerView.setLayoutManager(new LinearLayoutManager(view.getContext(), LinearLayoutManager.HORIZONTAL, false));
        recyclerView.getItemAnimator().setChangeDuration(0);
        mCommodityAdapter = new CommodityAdapter();
        mCommodityAdapter.setOnItemSelectListener(this);
        recyclerView.setAdapter(mCommodityAdapter);
        recyclerView.setNestedScrollingEnabled(false);

        recyclerView2.setLayoutManager(new LinearLayoutManager(view.getContext(), LinearLayoutManager.HORIZONTAL, false));
        recyclerView2.getItemAnimator().setChangeDuration(0);
        mProductAdapter = new ProductAdapter(this);
        recyclerView2.setAdapter(mProductAdapter);
        recyclerView2.setNestedScrollingEnabled(false);

        refreshLayout.disableWhenHorizontalMove(true);
        refreshLayout.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout ptrFrameLayout) {
                mPresenter.start();
            }
        });
        ViewUtil.setViewSize(flChart, ScreenUtils.getScreenWidth(), (int) (ScreenUtils.getScreenWidth() * 0.9));
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);

        return rootView;
    }

//    @Override
//    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
//
//        super.onActivityCreated(savedInstanceState);
//    }

    public void checkIfHasNewMsg() {
        if (SessionManager.getDefault().isLogin()) {
            UserInfo user = SessionManager.getDefault().getUser();
            String userId = user.getUserId() + "";
            TokenInfo userToken = SessionManager.getDefault().getUserToken();
            String accessToken = userToken.getAccessToken();

            mPresenter.getIfHasNewMsg(userId, accessToken);
        }
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        mPresenter.destroy();
        super.onDestroy();
    }


    public static NewHomeIndexFragment newInstance() {
        return newInstance(Area.ALL);
    }

    public static NewHomeIndexFragment newInstance(Area area) {
        NewHomeIndexFragment fm = new NewHomeIndexFragment();
        Bundle args = new Bundle();
        args.putString("area", area.name());
        fm.setArguments(args);
        return fm;
    }

    @OnClick(R2.id.tv_marquee_detail)
    public void onMarqueeClicked() {
        int currentPosition = marquee.getPosition();
        String target = marqueeInfos.get(currentPosition).getTarget();

        if (!"0".equals(target)) {
            if (!SessionManager.getDefault().isLogin()) {
                AppRouter.routeToLogin(getActivity());
                return;
            }
        }

        switch (target) {
            case "0":
                break;
            case "1":
                AppRouter.routeToWeb(getContext(), marqueeInfos.get(currentPosition).getTargetUrl());
                break;
            case "2":
                AppRouter.routeToWelfareRank(getContext());
                break;
            case "3":
                AppRouter.routeToMessage(getContext());
                break;
            case "4":
                AppRouter.routeToRecharge(getContext());
                break;
            default:
                break;
        }
    }

    @Override
    public void onLoadBannerData(List<BannerInfo> data) {
        ArrayList<String> images = new ArrayList<>();
        urls = new ArrayList<>();
        for (int i = 0; i < data.size(); i++) {
            images.add(data.get(i).getPicUrl());
            urls.add(data.get(i).getJumpUrl());
        }
        banner.setDelayTime(4000);
        banner.setImageLoader(new ImageLoader() {
            @Override
            public void displayImage(Context context, Object o, ImageView imageView) {
                Glide.with(context).load((String) o).into(imageView);
            }
        });
        banner.setImages(images);
        banner.isAutoPlay(false);
        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int i) {

                //跳转到网页操作
                if (TextUtils.isEmpty(urls.get(i))) {
                    return;
                }
                if ("Nojump".equals(urls.get(i))) {
                    return;
                }
                //未登录先登录
                if (!SessionManager.getDefault().isLogin()) {
                    AppRouter.routeToLogin(getActivity());
                    return;
                }
                //跳转外部浏览器
                if (urls.get(i).contains("type=web")){
                    Uri uri = Uri.parse(urls.get(i));
                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                    startActivity(intent);
                    return;
                }
                AppRouter.routeToWeb(getContext(), urls.get(i));
            }
        });
        banner.start();
    }


    @Override
    public void onLoadComplete() {
        if (refreshLayout == null) return;
        refreshLayout.refreshComplete();
    }

    @Override
    public void refreshCompleted() {
        if (refreshLayout != null && refreshLayout.isRefreshing()) {
            refreshLayout.refreshComplete();
        }
    }

    @Override
    public Area getArea() {
        return Area.typeOf(getArguments().getString("area"));
    }

    @Override
    public void onLoadBannerFailed(String s) {

    }

    @Override
    public void onLoadServiceQQSuccess(String url) {
        try {
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
        } catch (Exception e) {
            new DialogBuilder(getContext())
                    .setMessage("启动QQ失败，QQ号码已经复制，请前往QQ添加我们的客服QQ。")
                    .negativeButtonHidden()
                    .show();
        }
    }

    @Override
    public void onLoadServiceQQFailed(String msg) {

    }

    @Override
    public void hideLoading() {
        AppUI.dismiss();
    }

    @Override
    public void showLoading() {
        AppUI.loading(getContext());
    }

    @Override
    public void onLoadMarquee(List<NewMarqueeInfo> list) {
        this.marqueeInfos = list;
        ArrayList<String> marqueeList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            marqueeList.add(list.get(i).getMessage());
        }
        marquee.startWithList(marqueeList);
    }

    @Override
    public void onLoadHomeIndexData(HomeIndexInfo homeIndexInfo) {
        this.homeIndexInfo = homeIndexInfo;
        productPosition = 0;
        stairPosition = 0;
        quotationProductInfoList = new ArrayList<>();
        for (QuotationProductInfo info : homeIndexInfo.getQuotations()) {
            list:
            for (HomeIndexProductInfo indexProductInfo : homeIndexInfo.getIndexDetailDtoList()) {
                if (indexProductInfo.getParent() != null
                        && indexProductInfo.getParent().getProductId().equals(info.getProductId())) {
                    if (indexProductInfo.getChild().size() > 0) {
                        quotationProductInfoList.add(info);
                        break list;
                    }
                }
            }
        }

        if (quotationProductInfoList.size() == 0){
            AppUI.toastInCenter(getContext(),"获取商品信息失败");
            return;
        }

        quotationProductInfo = quotationProductInfoList.get(0);

        //遍历该类型商品，关联商品
        for (HomeIndexProductInfo indexProductInfo : homeIndexInfo.getIndexDetailDtoList()) {
            if (indexProductInfo.getParent() != null
                    && indexProductInfo.getParent().getProductId().equals(quotationProductInfo.getProductId())) {
                productInfos = indexProductInfo.getChild();
                break;
            }
        }
        mCommodityAdapter.setQuotations(quotationProductInfoList);

        mProductAdapter.setData(productInfos);


        if (ifChartIsAdded) {
            getActivity().getSupportFragmentManager().beginTransaction()
                    .remove(simpleStockFragment).commitAllowingStateLoss();
        }
        simpleStockFragment = SimpleStockFragment.newInstance(quotationProductInfo.getProductId());
        getActivity().getSupportFragmentManager().beginTransaction()
                .replace(R.id.fl_chart, simpleStockFragment).commitAllowingStateLoss();
        ifChartIsAdded = true;
    }

    @Override
    public void onLoadTradeTimeInfo(TradeTimeInfo tradeTimeInfo) {

    }

    @Override
    public void onLoadBalanceFailed(String msg) {
        tvBalance.setText(msg);
    }

    @Override
    public void onLoadBalanceInfo(BalanceInfo balanceInfo) {
        tvBalance.setText(Rx.formatPrice(balanceInfo.getBalance()) + "元");
    }

    @Override
    public void onLoadOrderListFailed(String msg) {

    }

    @Override
    public void updateMyIncome(List<OrderInfo> infos) {
        if (!SessionManager.getDefault().isLogin()) {
            tvOrder.setText("--");
            return;
        }
        double income = 0;
        for (OrderInfo info : infos) {
            income = income + info.getPrifitDifferent();
        }
        //4舍五入两位
        BigDecimal b = new BigDecimal(income);
        income = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        tvOrder.setPrice(income);
    }

    @Override
    public void onUpdateQuotation(QuotationProductInfo quotationProductInfo) {
        mCommodityAdapter.update(quotationProductInfo);
    }

    @Override
    public void onLoadCouponFailed() {
        tvCoupon.setText("--");
    }

    @Override
    public void onLoadCouponSuccess(List<CouponInfo> couponValid, CouponResponseInfo couponResponseInfo) {
        couponInfos = couponValid;
        tvCoupon.setText(String.format("%s张", couponValid.size()));
    }

    @Override
    public void onLoadClosePrice(List<RankingInfo> rankingInfos) {
        rankingInfoList = rankingInfos;
    }

    @Override
    public void onLoadHelpSuccess(String s) {
        helpContent = s;
    }


    @Override
    public void onNoMoreData() {

    }

    @Override
    public void onEmptyData(String s) {

    }

    @Override
    public void onLoadData(List<ShipmentInfo> list) {

    }

    @Override
    public void onLoginExpired() {

    }

    @OnClick(R2.id.ll_ddxt)
    public void onDDXTClicked() {
        String xt = "http://www.dd.shzstr.cn/learn/index.html";
        AppRouter.routeToWeb(getContext(), "点点学堂", xt);
    }

    @OnClick(R2.id.ll_ddzx)
    public void onDDZXClicked() {
        String zx = "http://mp.weixin.qq.com/mp/homepage?__biz=MzUxMjYyMDk3Nw==&hid=2&sn=ab1046f525564604f07f2bf1af92f2a9#wechat_redirect";
        AppRouter.routeToWeb(getContext(), "点点资讯", zx);
    }

    @OnClick(R2.id.ll_ddq)
    public void onDDQClicked() {
        AppRouter.routeToWelfareMoments(getContext());
    }

    @OnClick(R2.id.ll_ddylb)
    public void onDDYLBClicked() {
        if (!SessionManager.getDefault().isLogin()) {
            AppRouter.routeToLogin(getActivity());
            return;
        }
        AppRouter.routeToWelfareRank(getContext());
    }

    @Override
    public void onSelectListener(ProductInfo productInfo, int position) {
        if (stairPosition != position) {
            stairPosition = position;
            productPosition = 0;
            productInfos = new ArrayList<>();
            quotationProductInfo = quotationProductInfoList.get(position);

            //遍历找到该类型的商品，关联商品
            for (HomeIndexProductInfo indexProductInfo : homeIndexInfo.getIndexDetailDtoList()) {
                if (indexProductInfo.getParent() != null && indexProductInfo.getParent().getProductId().equals(quotationProductInfo.getProductId())) {
                    productInfos = indexProductInfo.getChild();
                    break;
                }
            }
            mProductAdapter.setData(productInfos);
            getActivity().getSupportFragmentManager().beginTransaction()
                    .replace(R.id.fl_chart, SimpleStockFragment.newInstance(quotationProductInfo.getProductId()), "stock").commitAllowingStateLoss();

        }

    }

    @Override
    public void onItemSelectListener(View view, ProductInfo productInfo, int position) {
        productPosition = position;
    }

    @Subscribe
    public void onEvent(Fragment fragment) {
        if (fragment instanceof NewHomeIndexFragment) {
            if (isAdded() && mPresenter != null) {
                //
            }
            mPresenter.loadRepeated();
            mPresenter.loadBalanceAndCoupons();
        }
    }

    @Subscribe
    public void onEvent(LoginEvent loginEvent) {
        onLoadBalanceFailed("--");
        tvOrder.setText("--");
        onLoadCouponFailed();
        updateMyIncome(new ArrayList<OrderInfo>());
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            if (mPresenter == null) return;
            mPresenter.loadRepeated();
            mPresenter.loadBalanceAndCoupons();
            checkIfHasNewMsg();
        }
    }

    @OnClick(R2.id.btn_recharge)
    public void onToRechargeClicked() {
        if (!SessionManager.getDefault().isLogin()) {
            AppRouter.routeToLogin(getActivity());
            return;
        }
        AppRouter.routeToRecharge(getContext());
    }

//    @OnClick(R2.id.iv_customer_service)
//    public void onCustomerServiceClicked() {
//
//    }

    /**
     * 判断qq是否可用
     */
    public boolean isQQClientAvailable(Context context) {
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.tencent.mobileqq")) {
                    return true;
                }
            }
        }
        return false;
    }

//    @OnClick(R2.id.iv_guide)
//    public void onGuideClicked() {
//
//    }

//    @OnClick(R2.id.iv_help)
//    public void onHelpClicked() {
//
//    }

    private void popHelpDialog() {
        Dialog helpDialog = new Dialog(getContext(), R.style.HelpDialog);
        Window window = helpDialog.getWindow();
        window.requestFeature(Window.FEATURE_NO_TITLE);
        window.setGravity(Gravity.RIGHT | Gravity.TOP);
        window.setDimAmount(0f);
        helpDialog.setContentView(com.baibei.product.R.layout.dialog_pop_help);
        WindowManager.LayoutParams lp = window.getAttributes();
        ViewGroup.LayoutParams layoutParams = ivHelp.getLayoutParams();
        lp.x = dip2px(getContext(), 58);
        lp.y = dip2px(getContext(), 39);
        JustifyTextView tvHelp = helpDialog.findViewById(com.baibei.product.R.id.tv_help);
//        tvHelp.setText("\n1.  不支持持单过夜，凌晨2点将自动退订\n\n" +
//                "2.  每种规格的商品只能持单1笔，需退订后才可建新单\n\n" +
//                "3.  投资有风险，交易须谨慎，降低风险止盈止损范围（0-90%）\n");
        tvHelp.setText(helpContent+"\n");
        tvHelp.setMovementMethod(ScrollingMovementMethod.getInstance());

        helpDialog.show();
    }

    public static int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    @Override
    public void onLoadProductCouponSuccess(List<CouponInfo> couponInfos) {
        productCoupons = couponInfos;
        toTradeFragment = ToTradeFragment.newInstance(productInfos, productInfos.get(mProductAdapter.getClickPostion()), buyOrSell
                , couponInfos, mPresenter.getSuggestNumbers(), 30);
        toTradeFragment.show(getFragmentManager(), "totrade");
    }

    @Override
    public void onLoadProductCouponFailed() {
        ToastUtils.showShortToast("获取优惠券信息失败");
    }

    @Override
    public void onLoadXin(XinStatusInfo xinStatusInfo) {
        if (!"1".equals(xinStatusInfo.getNewAction())) {
            ivNew.setVisibility(View.GONE);
            return;
        }
        ivNew.setBackgroundResource(R.drawable.anim_xin);
        AnimationDrawable ani = (AnimationDrawable) ivNew.getBackground();
        ani.setOneShot(false);
        ani.start();
    }

    @Override
    public void onLoadMsgStatus(List<MsgStatusInfo> msgStatusInfos) {
        String state = msgStatusInfos.get(0).getState();
        if ("0".equals(state)) {
            ivXiaoxi.setImageResource(R.drawable.xiaoxi);
            return;
        }
        ivXiaoxi.setImageResource(R.drawable.xiaoxihong);
    }

    @Override
    public void onLoadCustomerWXCodeSuccess(CustomerWxInfo customerWxInfo) {
        this.customerWxInfo = customerWxInfo;
    }

    @OnClick(R2.id.tv_buy)
    public void onBuyClicked() {
        setClosePrice();

        if (!SessionManager.getDefault().isLogin()) {
            AppRouter.routeToLogin(getActivity());
            return;
        }

        buyOrSell = TradeType.BUY;

        mPresenter.getProductCoupon(productInfos.get(mProductAdapter.getClickPostion()).getProductId());

//        toTradeFragment = ToTradeFragment.newInstance(productInfos, productInfos.get(mProductAdapter.getClickPostion()), TradeType.BUY
//                , couponInfos, mPresenter.getSuggestNumbers(), 30);
//        toTradeFragment.show(getFragmentManager(), "totrade");
    }

    @OnClick(R2.id.tv_sell)
    public void onSellClicked() {
        setClosePrice();

        if (!SessionManager.getDefault().isLogin()) {
            AppRouter.routeToLogin(getActivity());
            return;
        }

        buyOrSell = TradeType.SELL;

        mPresenter.getProductCoupon(productInfos.get(mProductAdapter.getClickPostion()).getProductId());
    }

    @OnClick(R2.id.tv_float)
    public void onFloatClicked() {
        setClosePrice();

        if (!SessionManager.getDefault().isLogin()) {
            AppRouter.routeToLogin(getActivity());
            return;
        }
        String name = homeIndexInfo.getQuotations().get(stairPosition).getQuoteName();
        double close = homeIndexInfo.getQuotations().get(stairPosition).getClose();
        double lastPrice = quotationProductInfoList.get(stairPosition).getLastPrice();
        AppRouter.routeToPriceFloat(getContext(), stairPosition, close, lastPrice, name);
    }

    private void setClosePrice() {
        for (int i = 0; i < productInfos.size(); i++) {
            for (int j = 0; j < rankingInfoList.size(); j++) {
                if (productInfos.get(i).getProductId() != null &&
                        productInfos.get(i).getProductId().equals(rankingInfoList.get(j).getProductId())) {
                    productInfos.get(i).setClosePrice(rankingInfoList.get(j).getClose() + "");
                }
            }
        }
    }

    @OnClick(R2.id.lin_order)
    public void onOrderClicked() {
        if (!SessionManager.getDefault().isLogin()) {
            AppRouter.routeToLogin(getActivity());
            return;
        }
        AppRouter.routeToOrderCenter(getActivity());
    }

    @OnClick(R2.id.lin_coupon)
    public void onCouponClicked() {
        if (!SessionManager.getDefault().isLogin()) {
            AppRouter.routeToLogin(getActivity());
            return;
        }
        AppRouter.routeToTicket(getContext());
    }


    @OnClick({R2.id.iv_customer_service, R2.id.tv_customer_service})
    public void onCustomerServiceClick() {
        final Dialog dialog = new Dialog(getContext(), 0);
        Window window = dialog.getWindow();
        window.requestFeature(Window.FEATURE_NO_TITLE);
        window.setGravity(Gravity.BOTTOM);
        WindowManager.LayoutParams attributes = window.getAttributes();
        attributes.y = 20;
        window.setAttributes(attributes);
        View view = LayoutInflater.from(getContext()).inflate(R.layout.layout_customer_service, null);
        TextView cuPhone = view.findViewById(R.id.tv_cuPhone);
        TextView cuQQ = view.findViewById(R.id.tv_cuQQ);
        TextView cuWX1 = view.findViewById(R.id.tv_wx1);
        TextView cuWX2 = view.findViewById(R.id.tv_wx2);
        if (customerWxInfo != null){
            cuWX1.setText("微信客服1: "+customerWxInfo.getWxcode1()+" (点击复制)");
            cuWX2.setText("微信客服2: "+customerWxInfo.getWxcode2()+" (点击复制)");
        } else {
            AppUI.toast(getContext(),"获取客服微信出错，请稍后重试或使用其他客服途径");
        }

        cuPhone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent dialIntent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:4000925288"));
                startActivity(dialIntent);
                dialog.dismiss();
            }
        });
        cuQQ.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //跳转qq
                if (!isQQClientAvailable(getContext())) {
                    new DialogBuilder(getContext()).negativeButtonHidden().setMessage("您的设备还未安装QQ客户端，不能进行临时会话！").show();
                    dialog.dismiss();
                    return;
                }
                mPresenter.getServiceQQ();
            }
        });
        cuWX1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (customerWxInfo == null){
                    return;
                }
                ClipboardManager clipBoard = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
                ClipData clipData = ClipData.newPlainText(null, customerWxInfo.getWxcode1());
                clipBoard.setPrimaryClip(clipData);
                AppUI.toast(getContext(),"复制成功，请去微信添加！");
            }
        });

        cuWX2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (customerWxInfo == null){
                    return;
                }
                ClipboardManager clipBoard = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
                ClipData clipData = ClipData.newPlainText(null, customerWxInfo.getWxcode2());
                clipBoard.setPrimaryClip(clipData);
                AppUI.toast(getContext(),"复制成功，请去微信添加！");
            }
        });

        dialog.setContentView(view);
        dialog.show();
    }

    @OnClick({R2.id.iv_guide, R2.id.tv_guide})
    public void onGuideClicked() {
        AppRouter.routeToNewhand(getContext());
    }

    @OnClick({R2.id.iv_help, R2.id.tv_help})
    public void onHelpClicked() {
        popHelpDialog();
    }


    @OnClick(R2.id.iv_xiaoxi)
    public void onMsgClicked() {
        if (!SessionManager.getDefault().isLogin()) {
            AppRouter.routeToLogin(getActivity());
            return;
        }
        ivXiaoxi.setImageResource(R.drawable.xiaoxi);
        AppRouter.routeToMessage(getContext());

    }

    @OnClick(R2.id.img_full_screen)
    public void onFullScreenClicked() {
        if (quotationProductInfo == null) return;
        AppRouter.routeToKLine(getActivity(), quotationProductInfo.getProductId());
    }
}
